package thread;

import java.util.concurrent.ThreadPoolExecutor;

public class demo28 {
    static class  MyBlockingQueue {
        //使用循环数组模拟实现队列
        int[] arr;
        private int size = 0;//统计元素个数
        private int head = 0;
        private int tail = 0;

        public MyBlockingQueue(int capacity) {
            this.arr = new int[capacity];
        }

        public void put(int elem) throws InterruptedException {

            synchronized (this) {
                while (size >= arr.length) {
                    //队列满了需要阻塞等待
                    //此处建议使用while---作二次判断
                    this.wait();
                }
                //等待结束可以正常插入
                arr[tail] = elem;
                tail++;
                if (tail >= 100) tail = 0;
                // tail = (tail + 1) % data.length;
                size++;
                this.notifyAll();
            }
        }

        public int take() throws InterruptedException {
            synchronized (this) {
                while (size == 0) {
                    //说明队列是空的需要阻塞等待队列不为空
                    this.wait();
                }
                //队列不为空了
                int ret = arr[head];
                head++;
                if (head >= 100) head = 0;
                size--;
                this.notifyAll();
                return ret;
            }
        }
    }
        static  int i=0;
        public static void main(String[] args) {
            MyBlockingQueue bq=new MyBlockingQueue(100);
            Thread producer=new Thread(()->{
                //生产者线程
                while(true){
                    try {
                        bq.put(i);
                        System.out.println("生产一个元素"+i);
                        i++;
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

            Thread consumer=new Thread(()->{
                while (true){
                    try {
                        int p=bq.take();
                        System.out.println("消费一个元素"+p);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            producer.start();
            consumer.start();
        }

}
